<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
require_once ('./application/controllers/authenticate.php');

class user extends Authenticate {

    const user_PER_PAGE = 20;
    const user_PAGE_RANGE = 5;

    function __construct() {
        global $active_system_function;
        $active_system_function = 'admin/site/user/index';
        parent::__construct();
        $this->load->model('site_user_model');
        $this->load->model('admin_model');
        $this->load->library('upload');
    }

    protected function _eventLoadLayout() {
        $this->page['title'] = 'Quản lý người dùng';
        $this->module['title'] = 'Quản lý người dùng';
    }

    function index() {
        try {
            global $active_system_function;
            $active_system_function = 'admin/site/user/index';
            $this->filtered_list('index');
        } catch (Exception $ex) {
            echo $ex->getMessage();
        }
    }

    private function check_has_privileges($data = array()) {
        $data['has_privilege_view'] = false;
        $data['has_privilege_new'] = false;
        $data['has_privilege_edit'] = false;
        $data['has_privilege_delete'] = false;
        if ($this->admin_model->is_admin()) {
            $data['has_privilege_view'] = true;
            $data['has_privilege_new'] = true;
            $data['has_privilege_edit'] = true;
            $data['has_privilege_delete'] = true;
        } else {
            $privileges = $this->admin_model->get_privileges();
            if (isset($privileges['admin/site/user/view'])) {
                $data['has_privilege_view'] = true;
            }
            if (isset($privileges['admin/site/user/new'])) {
                $data['has_privilege_new'] = true;
            }
            if (isset($privileges['admin/site/user/edit'])) {
                $data['has_privilege_edit'] = true;
            }
            if (isset($privileges['admin/site/user/delete'])) {
                $data['has_privilege_delete'] = true;
            }
        }
        return $data;
    }

    protected function _initData($return_url, $data = array()) {
        $filters = $this->input->post('filters');
        $current_page = intval($this->input->post('current_page'));
        $record_per_page = intval($this->input->post('record_per_page'));
        if ($record_per_page == 0) {
            $record_per_page = self::user_PER_PAGE;
        }
        $conds = null;

        if (!empty($filters['id'])) {
            $conds['id'] = 'id =' . $filters['id'];
        }

        if (!empty($filters['username'])) {
            $conds['username'] = 'username LIKE "%' . $filters['username'] . '%"';
        }

        if (!empty($filters['email'])) {
            $conds['email'] = 'email LIKE "%' . $filters['email'] . '%"';
        }

        if (!empty($filters['created_at_from'])) {
            $created_at_from = get_time_stamp($filters['created_at_from']);
            $conds['created_date'] = 'created_date >= ' . $created_at_from;
        }
        if (!empty($filters['created_at_to'])) {
            $created_at_to = get_time_stamp($filters['created_at_to']);
            if (isset($created_at_from)) {
                if ($created_at_from >= $created_at_to) {
                    $conds['created_date'] = 'created_date >= ' . $created_at_to;
                    $filters['created_at_from'] = date('d/m/Y', $created_at_to);
                }
            }
            $conds['created_date'] = 'created_date <= ' . get_time_stamp($filters['created_at_to'], true);
        }

        if(isset($filters['user_type']) && (int)$filters['user_type'] > 0){
            $conds['user_type'] = 'user_type = ' . $filters['user_type'];
        }

        if(isset($filters['is_active']) && (int)$filters['is_active'] > 0){
            $conds['is_active'] = 'is_active = ' . $filters['is_active'];
        }

        if (count($conds) == 0) {
            $query = 'SELECT COUNT(id) as count_result FROM site_user LIMIT 0, 1';
        } else {
            $query = 'SELECT COUNT(id) as count_result FROM site_user WHERE ' . implode(' AND ', $conds) . ' LIMIT 0, 1';
        }

        // Get Count user
        $rs = $this->site_user_model->db->query($query);
        $count_results = $rs->row()->count_result;
        $rs->free_result();

        // Paginate
        if ($current_page <= 1) {
            $current_page = 1;
        }
        $start = ($current_page - 1) * $record_per_page;
        if ($start <= 0) {
            $start = 0;
        }
        $total_pages = ceil($count_results / $record_per_page);
        $delta = ceil(self::user_PAGE_RANGE / 2);
        if ($current_page - $delta > $total_pages - self::user_PAGE_RANGE) {
            $pag['lower'] = $total_pages - self::user_PAGE_RANGE;
            $pag['upper'] = $total_pages;
        } else {
            if ($current_page - $delta < 0) {
                $delta = $current_page;
            }
            $offset = $current_page - $delta;
            $pag['lower'] = $offset + 1;
            $pag['upper'] = $offset + self::user_PAGE_RANGE;
        }
        if ($pag['lower'] <= 1) {
            $pag['lower'] = 1;
        }
        if ($pag['upper'] >= $total_pages) {
            $pag['upper'] = $total_pages;
        }
        $pag['total'] = $total_pages;

        // Transfer Variables
        $data['return_url'] = $return_url;
        $data['record_per_page'] = $record_per_page;
        $data['count_total']  = $count_results;
        $data['current_page'] = $current_page;
        $data['paginator']    = $pag;
        $data['filters']      = $filters;
        $data['collection']   = $this->site_user_model->get_collection($start, $record_per_page, $conds, ' id DESC');
        $data['save_action']  = site_url('admin/site/user/save', true);
        return $data;
    }

    public function filtered_list($alias) {
        try {
            $privileges = $this->check_has_privileges();
            $ajax_action = $this->input->getParam('ajax_action');
            $data = $this->_initData($alias, $privileges);
            $data['form_action'] = site_url('admin/site/user/filtered_list/'.$alias , true);
            if (empty($ajax_action)) {
                $this->setPageContent('admin/site/user/grid', $data);
                $this->renderLayout('layouts/fullcolumn');
            } else {
                $this->setPageContent('admin/site/user/ajax/list', $data);
                $this->renderLayout('layouts/ajax');
            }

        } catch (Exception $ex) {
            echo $ex->getMessage();
        }
    }

    function save() {
        try {
            $id = $this->input->post('id');
            $data = $this->input->post('data');

            $set_img_url = $this->input->post('set_img_url');
            $img_path    = $this->input->post('img_path');
            $updated_time = time();

            // Config Upload
            $config['allowed_types'] = 'gif|jpg|png|bmp|psd';
            $config['max_size'] = '500';
            $config['upload_path'] = './media/uploaded/' . date('Y', $updated_time) . '/' . date('m', $updated_time) . '/' . date('d', $updated_time) . '/';
            if (!file_exists($config['upload_path'])) {
                mkdir($config['upload_path'], 0777, true);
            }

            if (isset($data['password'])) {
                $data['password'] = trim($data['password']);
            }
            if (empty($data['password'])) {
                unset($data['password']);
            } else {
                $data['password'] = md5($data['password']);
            }

            if (empty($id)) {
                if (isset($_FILES['data_image']) && $_FILES['data_image']['size'] > 0) {
                    if ($set_img_url) {
                        if (!empty($img_path)) {
                            $data['avatar'] = $img_path;
                        }
                    } else {
                        $this->upload->initialize($config);
                        $this->upload->do_upload('data_image');
                        // Render Image Path
                        $data_upload = $this->upload->data();
                        $image_path = $config['upload_path'] . $data_upload['file_name'];
                        if (strlen($data_upload['file_name']) > 0) {
                            $data['avatar'] = $image_path;
                        }
                    }
                } else {
                    if ($set_img_url) {
                        if (!empty($img_path)) {
                            $data['avatar'] = $img_path;
                        }
                    }
                }

                $privileges = $this->check_has_privileges();
                if (!$privileges['has_privilege_new']) {
                    $this->st_registry->register('admin/site/user/error', 'Bạn không có quyền tạo người dùng mới');
                    redirect(site_url('admin/site/user/index', true));
                    exit();
                }

                $id = $this->site_user_model->add_user($data);
                $this->st_registry->register('admin/site/user/success', 'Thêm người dùng thành công');
            } else {
                $privileges = $this->check_has_privileges();
                if (!$privileges['has_privilege_edit']) {
                    $this->st_registry->register('admin/site/user/error', 'Bạn không có quyền sửa người dùng này');
                    redirect(site_url('admin/site/user/index', true));
                    exit();
                }

                $user = $this->site_user_model->load_by_id($id);

                if (isset($_FILES['data_image']) && $_FILES['data_image']['size'] > 0) {
                    if ($set_img_url) {
                        if (!empty($img_path)) {
                            $data['avatar'] = $img_path;
                        }
                    } else {
                        $this->upload->initialize($config);
                        $this->upload->do_upload('data_image');
                        // Render Image Path
                        $data_upload = $this->upload->data();
                        $image_path = $config['upload_path'] . $data_upload['file_name'];
                        if (strlen($data_upload['file_name']) > 0) {
                            $data['avatar'] = $image_path;
                        }
                    }
                } else {
                    if ($set_img_url) {
                        if (!empty($img_path)) {
                            $data['avatar'] = $img_path;
                        }
                    }
                }
                if (!isset($data['avatar'])) {
                    $data['avatar'] = $user->avatar;
                }

                $this->site_user_model->update_user($id, $data);
                $this->st_registry->register('admin/site/user/success', 'Sửa thông tin người dùng thành công');
            }
        } catch (Exception $ex) {
            $this->st_registry->register('admin/site/user/error', 'Lỗi xảy ra: ' . $ex->getMessage());
        }
        redirect(site_url('admin/site/user/index', true));
    }

    function edit() {
        try {

            global $active_user_function;
            $active_user_function = 'admin/site/user/index';
            $data = $this->check_has_privileges();

            $id = $this->input->getParam('id');
            $data['user']    = $this->site_user_model->load_by_id($id);
            $data['save_action'] = site_url('admin/site/user/save', true);

            $this->setPageContent('admin/site/user/edit', $data);
            $this->renderLayout('layouts/fullcolumn');
        } catch (Exception $ex) {
            $this->st_registry->register('admin/site/user/error', 'Lỗi xảy ra: ' . $ex->getMessage());
        }
    }

    function delete() {
        try {
            $privileges = $this->check_has_privileges();
            $id = intval(trim($this->input->getParam('id')));
            if (empty($id)) {
                $this->st_registry->register('admin/site/user/error', 'Không xác định được người dùng cần xóa (ID)?');
                redirect(site_url('admin/site/user/index', true));
                exit();
            }
            if (!$privileges['has_privilege_delete']) {
                $this->st_registry->register('admin/site/user/error', 'Bạn không có quyền xóa người dùng này');
                redirect(site_url('admin/site/user/index', true));
                exit();
            }
            $this->site_user_model->delete_user($id);
            $this->st_registry->register('admin/site/user/success', 'Xóa người dùng thành công');
        } catch (Exception $ex) {
            $this->st_registry->register('admin/site/user/error', 'Lỗi xảy ra: ' . $ex->getMessage());
        }
        redirect(site_url('admin/site/user/index', true));
    }
}